package org.amicofragile.test.springintegration.transformation;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.amicofragile.test.springintegration.dto.Person;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.annotation.Transformer;

public class MailToPersonTransformer
{
	private static final Log LOG = LogFactory.getLog(MailToPersonTransformer.class);
	
	@Transformer
	public Person parseEmail(final MimeMessage message)
	{
		LOG.debug("MailToPersonTransformer.parseEmail");
		InternetAddress from;
		Person person = new Person();
		try
		{
			from = (InternetAddress )message.getFrom()[0];
			LOG.debug("Processing mail from: " + from.getAddress() + " <" + from.getPersonal() + ">");
			final String bodyText = message.getContent().toString().trim();
			final String[] rows = bodyText.split("\n");
			if(rows.length == 2)
			{
				final String nome = rows[0].substring(rows[0].indexOf(':') + 1).trim();
				final String cognome = rows[1].substring(rows[1].indexOf(':') + 1).trim();
				person.setName(nome);
				person.setSurname(cognome);
			}
			
		} catch (MessagingException e)
		{
			LOG.error("Messaging error processing email message", e);
		} catch (IOException e)
		{
			LOG.error("I/O error processing email message", e);
		}
		return person;
	}
}
